package io.lkt.modules.sys.controller;

import com.google.common.collect.Lists;
import io.lkt.common.redis.RedisCacheUtil;
import io.lkt.common.util.Query;
import io.lkt.common.util.SpringContextUtil;
import io.lkt.common.utils.AliyunOssClientUtil;
import io.lkt.common.utils.PageUtils;
import io.lkt.common.utils.R;
import io.lkt.common.validator.ValidatorUtils;
import io.lkt.modules.job.utils.HttpGetPostUtils;
import io.lkt.modules.sys.entity.*;
import io.lkt.modules.sys.redis.SysConfigRedis;
import io.lkt.modules.sys.sensitive.SensitiveFilter;
import io.lkt.modules.sys.service.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

import io.lkt.modules.sys.utils.SysConstant;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping({"/sys/barticleinfo"})
public class BArticleInfoController
        extends AbstractController
{
    private static final Logger logger = LoggerFactory.getLogger(BArticleInfoController.class);
    @Autowired
    private BPunchClockArticleInfoService bPunchClockArticleInfoService;
    @Autowired
    private BUserShareArticleInfoService bUserShareArticleInfoService;
    @Autowired
    private BArticleInfoService bArticleInfoService;
    @Autowired
    private BArticleTypeInfoService bArticleTypeInfoService;
    @Autowired
    BBrandInfoService bBrandInfoService;
    @Autowired
    BUserInfoService bUserInfoService;
    @Autowired
    SysConfigRedis redisTemplate;
    @Autowired
    RedisCacheUtil redisCacheUtil;
    @Autowired
    PythonArticleInfoService pythonArticleInfoService;
    @Value("${serviceUrls}")
    private String serviceUrls;
    @Autowired
    SysUserRoleService sysUserRoleService;
    @Autowired
    BArticleGzhService bArticleGzhService;

    @RequestMapping({"/articleUrl"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    public R articleUrl(HttpServletRequest request)
    {
        String url = request.getParameter("url");
        String href = "";
        Map<String, Object> map = new HashMap();
        try
        {
            href = urlMap(url);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return R.ok().put("map", href);
    }

    public String urlMap(String url)
            throws Exception
    {
        Map<String, Object> map = new HashMap();
        Document document = Jsoup.connect(url).get();
        Elements a = document.getElementsByTag("html");
        Elements img = document.select("img");
        List<String> list = new ArrayList();
        for (Element ele : img)
        {
            String src = "<img src=\"" + ele.absUrl("src") + '"' + "/>";
            list.add(src);
        }
        map.put("text", a.html());
        map.put("img", list);
        return a.html();
    }

    @RequestMapping({"/list"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    public R list(@RequestParam Map<String, Object> params)
            throws Exception
    {
        PageUtils page = this.bArticleInfoService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/listForUserId")
//    @RequiresPermissions("sys:bteamrelation:listForUserId")
    public R listForUserId(@RequestParam Map<String, Object> params) {
        PageUtils page = bArticleInfoService.queryPageForUserId(params);

        List<?> list = page.getList();

        if (CollectionUtils.isNotEmpty(list)) {
            List<BArticleInfoEntity> bArticleInfoList = Lists.newArrayList();

            for (Object temp : list) {
                BArticleInfoEntity bArticleInfo = (BArticleInfoEntity) temp;
                // 分类
                if ((bArticleInfo.getArticleTypeId() != null) && (!bArticleInfo.getArticleTypeId().equals(""))) {
                    BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.getById(bArticleInfo.getArticleTypeId());
                    if (bArticleTypeInfoEntity != null) {
                        bArticleInfo.setArticleTypeName(bArticleTypeInfoEntity.getArticleTypeName());
                    }
                }

                // 品牌
                if ((bArticleInfo.getArticleBrandId() != null) && (!bArticleInfo.getArticleBrandId().equals(""))) {
                    BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.getById(bArticleInfo.getArticleBrandId());
                    if (bBrandInfoEntity != null) {
                        bArticleInfo.setArticleTypeName(bBrandInfoEntity.getBrandName());
                    }
                }

                bArticleInfoList.add(bArticleInfo);
            }

            page.setList(bArticleInfoList);
        }

        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/shareListForUserId")
//    @RequiresPermissions("sys:bteamrelation:listForUserId")
    public R shareListForUserId(@RequestParam Map<String, Object> params) {
        PageUtils page = bUserShareArticleInfoService.queryPageForUserId(params);

        List<?> list = page.getList();

        if (CollectionUtils.isNotEmpty(list)) {
            List<BArticleInfoEntity> bArticleInfoList = Lists.newArrayList();

            for (Object temp : list) {
                BUserShareArticleInfoEntity info = (BUserShareArticleInfoEntity) temp;

                BArticleInfoEntity bArticleInfo = new BArticleInfoEntity();
                bArticleInfo.setId(info.getArticleId());
                if(info.getArticleCategory() == 1) {
                    bArticleInfo = bArticleInfoService.getById(info.getArticleId());
                    bArticleInfo.setShareId(info.getId());
                    bArticleInfo.setShareTime(info.getCreateTime());
                    // 分类
                    if ((bArticleInfo.getArticleTypeId() != null) && (!bArticleInfo.getArticleTypeId().equals(""))) {
                        BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.getById(bArticleInfo.getArticleTypeId());
                        if (bArticleTypeInfoEntity != null) {
                            bArticleInfo.setArticleTypeName(bArticleTypeInfoEntity.getArticleTypeName());
                        }
                    }

                    // 品牌
                    if ((bArticleInfo.getArticleBrandId() != null) && (!bArticleInfo.getArticleBrandId().equals(""))) {
                        BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.getById(bArticleInfo.getArticleBrandId());
                        if (bBrandInfoEntity != null) {
                            bArticleInfo.setArticleTypeName(bBrandInfoEntity.getBrandName());
                        }
                    }
                }

                if(info.getArticleCategory() == 2) {
                    BPunchClockArticleInfoEntity clockArticle = bPunchClockArticleInfoService.getById(info.getArticleId());

                    if(clockArticle!=null) {
                        bArticleInfo.setShareId(info.getId());
                        bArticleInfo.setShareTime(info.getCreateTime());
                        bArticleInfo.setArticleTitle(clockArticle.getClockArticleTitle());
                        bArticleInfo.setCreateTime(clockArticle.getClockArticleTime());
                        bArticleInfo.setArticleTypeName("");
                        bArticleInfo.setResourceType(clockArticle.getClockArticleTimeType());
                        bArticleInfo.setArticleSource(1);
                    }
                }
                bArticleInfoList.add(bArticleInfo);
            }

            page.setList(bArticleInfoList);
        }

        return R.ok().put("page", page);
    }

    @RequestMapping({"/queryList"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    public R queryList(@RequestParam Map<String, Object> params)
    {
        //System.out.println(params);

        SysUserEntity curUser= getUser();
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(curUser.getUserId());
        params.put("userGzhList", userGzhList);

        Query query = new Query(params);
        List<BArticleInfoEntity> brandList = this.bArticleInfoService.queryList(query);
        //System.out.println(brandList.size());
        for (BArticleInfoEntity bArticleInfoEntity : brandList)
        {
            if ((bArticleInfoEntity.getCreateUser() != null) && (!bArticleInfoEntity.getCreateUser().equals(""))) {
                bArticleInfoEntity.setUserName(bArticleInfoEntity.getCreateUser());
            } else if ((bArticleInfoEntity.getArticleSource() != null) && (bArticleInfoEntity.getArticleSource().intValue() == 1)) {
                bArticleInfoEntity.setUserName("管理员");
            }
            if (bArticleInfoEntity.getArticleTypeId() == null)
            {
                BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.getById(bArticleInfoEntity.getArticleBrandId());
                if (bBrandInfoEntity != null) {
                    bArticleInfoEntity.setArticleTypeName(bBrandInfoEntity.getBrandName());
                }
            }
            else
            {
                BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.getById(bArticleInfoEntity.getArticleTypeId());
                if (bArticleTypeInfoEntity != null) {
                    bArticleInfoEntity.setArticleTypeName(bArticleTypeInfoEntity.getArticleTypeName());
                }
            }
        }
        int total = this.bArticleInfoService.queryTotal(query).intValue();
        PageUtils pageUtil = new PageUtils(brandList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @RequestMapping({"/info/{id}"})
    @RequiresPermissions({"sys:barticleinfo:info"})
    public R info(@PathVariable("id") Integer id)
    {
        BArticleInfoEntity bArticleInfo = this.bArticleInfoService.getById(id);
        int type = 0;
        if (bArticleInfo.getArticleBrandId() != null)
        {
            BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.getById(bArticleInfo.getArticleBrandId());
            if (bBrandInfoEntity != null) {
                bArticleInfo.setBrandName(bBrandInfoEntity.getBrandName());
            }
        }
        if (bArticleInfo.getArticleTypeId() != null)
        {
            BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.getById(bArticleInfo.getArticleTypeId());
            if (bArticleTypeInfoEntity != null) {
                bArticleInfo.setArticleTypeName(bArticleTypeInfoEntity.getArticleTypeName());
            }
            type = 1;
        }

        // 文章关联公众号
        BArticleGzh bArticleGzhSelect = this.bArticleGzhService.queryByArticleId(id);

        if(bArticleGzhSelect != null) {
            bArticleInfo.setGzhCode(bArticleGzhSelect.getGzhCode());
        }else{
            bArticleInfo.setGzhCode("-1");
        }

        // 查询头条标题id start yl 20200624
        List<Integer> headlineTitleIds = this.bArticleInfoService.selectHeadlineIdsByArticleId(id);
        if (CollectionUtils.isNotEmpty(headlineTitleIds)){
            bArticleInfo.setHeadlineTitleIds( headlineTitleIds
                    .stream()
                    .map(headlineTitleId -> headlineTitleId +"")
                    .collect(Collectors.joining(",")));
        }
        // 查询头条标题id end yl 20200624
        JSONArray jsonArray = new JSONArray();
        String content = bArticleInfo.getArticleContent();
        if (bArticleInfo.getArticleVersionNum().intValue() == 1) {
            try
            {
                jsonArray = JSONArray.fromObject(bArticleInfo.getArticleContent());
            }
            catch (Exception e)
            {
                System.out.println("文章内容存在问题：" + content);
                String error = "[{\"textContent\": \"文章内容有误\",\"textType\": 1}]";
                jsonArray = JSONArray.fromObject(error);
            }
        }
        return R.ok().put("bArticleInfo", bArticleInfo).put("type", Integer.valueOf(type)).put("jsonArray", jsonArray);
    }

    @RequestMapping({"/save"})
    @RequiresPermissions({"sys:barticleinfo:save"})
    public R save(@RequestBody BArticleInfoEntity bArticleInfo)
    {
        if ((bArticleInfo.getBrandName().equals("")) && (bArticleInfo.getArticleTypeName().equals(""))) {
            return R.error("你好，请选择文章品牌或文章分类！");
        }
        if ((bArticleInfo.getArticleTitle() == null) || (bArticleInfo.getArticleDesc() == null) || (bArticleInfo.getArticleContent() == null)) {
            return R.error("你好，文章标题、概述、内容不能为空！");
        }

        for(String k: SysConstant.KeyWorks){
            if(bArticleInfo.getArticleTitle()!=null && bArticleInfo.getArticleTitle().contains(k)){
                return R.error("标题中不能包含“"+k+"”，请检查后修正.");
            }
            if(bArticleInfo.getArticleDesc()!=null && bArticleInfo.getArticleDesc().contains(k)){
                return R.error("配文中不能包含“"+k+"”，请检查后修正.");
            }
        }

        Integer resultId = 0;
        // 使用默认单例（加载默认词典）
        SensitiveFilter filter =new SensitiveFilter(new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("sensi_words.txt"), StandardCharsets.UTF_8)));
//        SensitiveFilter filter = SensitiveFilter.DEFAULT;

        //文章标题+"占位符"，防止工具类筛选掉两个字符串的标题
        String textTitle = bArticleInfo.getArticleTitle()+"文章标题";

        //文章标题进行过滤
        String filtedTitle = filter.filter(textTitle, '▓')+"文章标题";

        // 如果未过滤，则返回输入的String引用
        if (filtedTitle.contains("▓▓")) {
            // 句子中有敏感词
            //找出可能第一个敏感词语
            int length = Math.min(filtedTitle.length(), textTitle.length());
            int pos = 0;
            while (pos < length) {
                if (0 != (filtedTitle.charAt(pos) ^ textTitle.charAt(pos))) {
                    break;
                }
                pos++;
            }

            return R.error("您好，文章标题中含有敏感关键字【"+ textTitle.substring(pos, pos + 2) +"】哦");
        }

        //文章概述
        String textDesc = bArticleInfo.getArticleDesc()+"文章概述";

        //文章概述进行过滤
        String filtedDesc = filter.filter(textDesc, '▓')+"文章概述";

        // 如果未过滤，则返回输入的String引用
        if (filtedDesc.contains("▓▓")) {
            // 句子中有敏感词
            //找出可能第一个敏感词语
            int length = Math.min(filtedDesc.length(), textDesc.length());
            int pos = 0;
            while (pos < length) {
                if (0 != (filtedDesc.charAt(pos) ^ textDesc.charAt(pos))) {
                    break;
                }
                pos++;
            }

            return R.error("您好，文章概述中含有敏感关键字【"+ textDesc.substring(pos, pos + 2) +"】哦");
        }

        //文章内容
        String textContent = bArticleInfo.getArticleContent();

        //文章内容进行过滤
        String filtedContent = filter.filter(textContent, '▓');

        // 如果未过滤，则返回输入的String引用
        if (filtedContent.contains("▓▓")) {
            // 句子中有敏感词
            //找出可能第一个敏感词语
            int length = Math.min(filtedContent.length(), textContent.length());
            int pos = 0;
            while (pos < length) {
                if (0 != (filtedContent.charAt(pos) ^ textContent.charAt(pos))) {
                    break;
                }
                pos++;
            }

//            return R.error("filtedContent="+filtedContent.length()+"textContent="+textContent.length());
            return R.error("您好，文章内容中含有敏感关键字【"+ textContent.substring(pos, pos + 2) +"】哦");
        }
        bArticleInfo.setCreateTime(new Date());
        bArticleInfo.setModifyTime(new Date());
        bArticleInfo.setArticleSource(Integer.valueOf(1));
        bArticleInfo.setArticleStatus(Integer.valueOf(1));
        bArticleInfo.setSpiderProcessStatus(Integer.valueOf(1));
        bArticleInfo.setArticleVersionNum(Integer.valueOf(2));
        bArticleInfo.setSType("后台录入");
        String textArticleTitle = bArticleInfo.getArticleTitle();//标题
        String textArticleDesc = bArticleInfo.getArticleDesc();//简介
        String textArticleContent = bArticleInfo.getArticleContent();//内容

        bArticleInfo.setArticleBrandId(null);
        bArticleInfo.setArticleTypeId(null);

        SysUserEntity curUser = getUser();
        bArticleInfo.setCreateUser(curUser.getUsername());
        if (!bArticleInfo.getBrandName().equals("")){
            String[] brandNames = bArticleInfo.getBrandName().split(",");
            if (brandNames != null) {
                for(int i = 0; i < brandNames.length; i++) {
                    BBrandInfoEntity brandInfoEntity = new BBrandInfoEntity();
                    brandInfoEntity.setId(this.bBrandInfoService.queryByName(brandNames[i]).getId());
                    if (brandInfoEntity == null) {
                        return R.error("所选的品牌不存在");
                    }

                    String brandNameMode = brandNames[i];//品牌

                    bArticleInfo.setArticleTitle(textArticleTitle.replaceAll("#BN#", brandNameMode));//标题
                    bArticleInfo.setArticleDesc(textArticleDesc.replaceAll("#BN#", brandNameMode));//简介
                    bArticleInfo.setArticleContent(textArticleContent);//内容
//                    bArticleInfo.setArticleContent(textArticleContent.replaceAll("#BN#", brandNameMode));//内容

//                    String brandNameModel = this.bBrandInfoService.queryTempByName(brandNames[i]).getTempContent();//品牌内容模板
//                    if(brandNameModel != null){
//                        bArticleInfo.setArticleContent(bArticleInfo.getArticleContent() + brandNameModel);//内容
//                    }

                    bArticleInfo.setArticleBrandId(brandInfoEntity.getId());
                    // 删除品牌 top50 缓存 start
                    String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + brandInfoEntity.getId();
                    redisCacheUtil.removeSingleCacheMaster(articleBrandIdKey);
                    // 删除品牌 top50 缓存 end
                    String brandId = bArticleInfo.getArticleBrandId().toString();
                    int total = this.bArticleInfoService.titleTotal(bArticleInfo.getArticleTitle(), brandId).intValue();
                    if (total == 0)
                    {
                        this.bArticleInfoService.setNullArticleTypeId(bArticleInfo.getId());
                        this.bArticleInfoService.save(bArticleInfo);
                        resultId = bArticleInfo.getId();

                        this.redisCacheUtil.removeSingleCache("recommendHotArticleInfo2ByBrandForHotValue" + brandInfoEntity.getId());
                        this.redisCacheUtil.removeSingleCache("recommendHotArticleInfoByBrandForHotValue" + brandInfoEntity.getId());
                        this.redisCacheUtil.removeSingleCache("recommendHotVideoInfoByBrandForHotValue" + brandInfoEntity.getId());
                        //this.redisCacheUtil.removeSingleCache("platformBrandArticle" + brandInfoEntity.getId());
                        // 向头条标题添加关联 start yl 20200624
                        if (StringUtils.isNoneBlank(bArticleInfo.getHeadlineTitleIds())){
                            this.headlineRelation(bArticleInfo.getId(), Arrays.stream(bArticleInfo.getHeadlineTitleIds()
                                    .split(","))
                                    .map(s -> Integer.valueOf(s.trim()))
                                    .collect(Collectors.toList()));
                        }
                        // 向头条标题添加关联 end yl 20200624
                        // 文章公众号关联
                        BArticleGzh bArticleGzhSave = new BArticleGzh();
                        // 文章id
                        bArticleGzhSave.setArticleId(bArticleInfo.getId());
                        // 公众号标识
                        bArticleGzhSave.setGzhCode(bArticleInfo.getGzhCode());
                        // 先删除
                        if(this.bArticleGzhService.queryByArticleId(bArticleInfo.getId()) != null) {
                            this.bArticleGzhService.deleteByArticleId(bArticleInfo.getId());
                        }
                        // 再保存
                        if((bArticleGzhSave.getGzhCode() != null) && (!bArticleGzhSave.getGzhCode().equals("-1")) && (!"".equals(bArticleGzhSave.getGzhCode().trim()))) {
                            this.bArticleGzhService.insertOne(bArticleGzhSave);
                        }
//                        return R.ok().put("total", Integer.valueOf(total));
                    }

                }
                return R.ok().put("resultId",resultId);
            }
            return R.error("所选的文章品牌不存在");
        }
        if (!bArticleInfo.getArticleTypeName().equals(""))
        {
            String[] typeNames = bArticleInfo.getArticleTypeName().split(",");
            if (typeNames != null) {
                for (int j = 0; j < typeNames.length; j++) {
                    BArticleTypeInfoEntity articleTypeInfoEntity = this.bArticleTypeInfoService.queryByName(typeNames[j]);
                    if (articleTypeInfoEntity != null)
                    {
                        bArticleInfo.setArticleTypeId(articleTypeInfoEntity.getId());
                        // 删除分类 top50 缓存 start
                        String articleTypeIdKey = SysConstant.PLANT_FORM_TYPE_ARTICLE_TOP50 + articleTypeInfoEntity.getId();
                        redisCacheUtil.removeSingleCacheMaster(articleTypeIdKey);
                        // 20210203 删除分类 top50 缓存 end
                        this.bArticleInfoService.setNullArticleBrandId(bArticleInfo.getId());
                        this.bArticleInfoService.save(bArticleInfo);
                        resultId = bArticleInfo.getId();

                        this.redisCacheUtil.removeSingleCache("recommendHotArticleInfo2ByTypeForHotValue" + articleTypeInfoEntity.getId());
                        this.redisCacheUtil.removeSingleCache("recommendHotArticleInfoByTypeForHotValue" + articleTypeInfoEntity.getId());
                        this.redisCacheUtil.removeSingleCache("recommendHotVideoInfoByTypeForHotValue" + articleTypeInfoEntity.getId());
                        //this.redisCacheUtil.removeSingleCache("platformTypeArticle" + articleTypeInfoEntity.getId());
                        // 向头条标题添加关联 start yl 20200624
                        if (StringUtils.isNoneBlank(bArticleInfo.getHeadlineTitleIds())){
                            this.headlineRelation(bArticleInfo.getId(), Arrays.stream(bArticleInfo.getHeadlineTitleIds()
                                    .split(","))
                                    .map(s -> Integer.valueOf(s.trim()))
                                    .collect(Collectors.toList()));
                        }
                        // 向头条标题添加关联 end yl 20200624
                        // 文章公众号关联
                        BArticleGzh bArticleGzhSave = new BArticleGzh();
                        // 文章id
                        bArticleGzhSave.setArticleId(bArticleInfo.getId());
                        // 公众号标识
                        bArticleGzhSave.setGzhCode(bArticleInfo.getGzhCode());
                        // 先删除
                        if(this.bArticleGzhService.queryByArticleId(bArticleInfo.getId()) != null) {
                            this.bArticleGzhService.deleteByArticleId(bArticleInfo.getId());
                        }
                        // 再保存
                        if((bArticleGzhSave.getGzhCode() != null) && (!bArticleGzhSave.getGzhCode().equals("-1")) && (!"".equals(bArticleGzhSave.getGzhCode().trim()))) {
                            this.bArticleGzhService.insertOne(bArticleGzhSave);
                        }
                    }
                }
                return R.ok().put("resultId",resultId);
            }
            return R.error("所选的文章类型不存在");
        }
        logger.info("新增文章:" + bArticleInfo.getArticleTitle());
        return R.error("新增文章失败");
    }

    /**
     * yl 20200623
     * 向头条标题关联文章
     * @param articleId
     * @param headlineTitleIds
     */
    private void headlineRelation(Integer articleId ,List<Integer> headlineTitleIds){
        if (null == articleId && CollectionUtils.isEmpty(headlineTitleIds)){
            return;
        }
        SysUserEntity curUser = getUser();
        this.bArticleInfoService.headlineRelation(articleId,headlineTitleIds,curUser.getUserId().intValue());
    }

    @RequestMapping({"/importArticlePython"})
    @RequiresPermissions({"sys:barticleinfo:save"})
    public R importArticlePython()
            throws Exception
    {
        Integer total = this.pythonArticleInfoService.noImportCount();

        HttpClient httpClient = HttpClientBuilder.create().build();
        String profile = SpringContextUtil.getActiveProfile();
        String url = "";
        if (profile.equals("dev")) {
            url = "http://120.24.243.155/spiderArticleDesc/";
        } else {
            url = "http://120.24.243.155/spiderArticleDesc/";
        }
        HttpPost post = new HttpPost(url);
        String json = "{\"data_id\":1}";
        StringEntity postingString = new StringEntity(json);
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());
        return R.ok().put("total", total);
    }

    @RequestMapping({"/importHtmlAll"})
    @RequiresPermissions({"sys:barticleinfo:save"})
    public R importArticleAll(@RequestBody Map<String, Object> params)
            throws Exception
    {
        ArrayList<String> ids = (ArrayList)params.get("ids");

        List<SpiderTaskEntity> spiderTaskEntities = new ArrayList();
        for (Iterator localIterator = ids.iterator(); localIterator.hasNext();)
        {
            String id = (String)localIterator.next();
            SpiderTaskEntity item = this.bArticleInfoService.getSpiderTaskById(Integer.valueOf(id));
            if (item != null) {
                spiderTaskEntities.add(item);
            }
        }
        Integer total = Integer.valueOf(0);
        Integer localInteger1;
        if ((spiderTaskEntities != null) && (spiderTaskEntities.size() > 0))
        {
            Integer localInteger2;
            for (Iterator id = spiderTaskEntities.iterator(); id.hasNext(); localInteger2 = total = Integer.valueOf(total.intValue() + 1))
            {
                SpiderTaskEntity ste = (SpiderTaskEntity)id.next();
                BArticleInfoEntity bArticleInfo = new BArticleInfoEntity();

                BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.queryByName(ste.getBrandName());
                BArticleTypeInfoEntity articleTypeInfoEntity = null;
                if (bBrandInfoEntity == null) {
                    articleTypeInfoEntity = this.bArticleTypeInfoService.queryByName(ste.getBrandName());
                }
                if (bBrandInfoEntity != null) {
                    bArticleInfo.setArticleBrandId(bBrandInfoEntity.getId());
                } else if (articleTypeInfoEntity != null) {
                    bArticleInfo.setArticleTypeId(articleTypeInfoEntity.getId());
                }
                if ((bArticleInfo.getArticleBrandId() != null) || (bArticleInfo.getArticleTypeId() != null))
                {
                    bArticleInfo.setCreateTime(new Date());
                    bArticleInfo.setModifyTime(new Date());
                    bArticleInfo.setArticleSource(Integer.valueOf(6));
                    bArticleInfo.setArticleStatus(Integer.valueOf(1));
                    bArticleInfo.setSpiderProcessStatus(Integer.valueOf(1));
                    bArticleInfo.setArticleVersionNum(Integer.valueOf(2));

                    SysUserEntity curUser = getUser();
                    bArticleInfo.setCreateUser(curUser.getUsername());

                    bArticleInfo.setArticleTitle(ste.getArticleTitle());

                    String articleImgUrl = ste.getArticleThumbnail();
                    if ((ste.getArticleThumbnail() != null) && (!ste.getArticleThumbnail().contains(AliyunOssClientUtil.ossImgUrl))) {
                        articleImgUrl = AliyunOssClientUtil.uploadFileByFileUrl2(ste.getArticleThumbnail());
                    }
                    bArticleInfo.setArticleImgUrl(articleImgUrl);

                    String articleContent = updateImgs(ste.getArticleContent());

                    bArticleInfo.setArticleContent(articleContent);
                    bArticleInfo.setArticleDesc(ste.getArticleBrief());
                    bArticleInfo.setSUrl(ste.getUrl());
                    bArticleInfo.setSId(ste.getId().toString());
                    bArticleInfo.setSType("爬虫导入");

                    this.bArticleInfoService.save(bArticleInfo);
                    logger.info("新增文章:" + bArticleInfo.getArticleTitle());

                    this.bArticleInfoService.updateImportStute(ste.getId());
                    localInteger1 = total;
                }
            }
        }
        return R.ok().put("total", total);
    }

    @RequestMapping({"/importArticle1"})
    @RequiresPermissions({"sys:barticleinfo:save"})
    public R importArticle1(@RequestBody Map<String, Object> params)
            throws Exception
    {
        ArrayList<String> ids = (ArrayList)params.get("ids");
        String brandName = (String)params.get("brandName");

        List<SpiderTaskEntity> spiderTaskEntities = new ArrayList();
        for (String id : ids)
        {
            SpiderTaskEntity item = this.bArticleInfoService.getSpiderTaskById(Integer.valueOf(id));
            if (item != null) {
                spiderTaskEntities.add(item);
            }
        }
        BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.queryByName(brandName);
        BArticleTypeInfoEntity articleTypeInfoEntity = null;
        if (bBrandInfoEntity == null) {
            articleTypeInfoEntity = this.bArticleTypeInfoService.queryByName(brandName);
        }
        Integer total = Integer.valueOf(0);
        Integer localInteger1;
        if ((spiderTaskEntities != null) && (spiderTaskEntities.size() > 0))
        {
            Integer localInteger2;
            for (Iterator localIterator2 = spiderTaskEntities.iterator(); localIterator2.hasNext(); localInteger2 = total = Integer.valueOf(total.intValue() + 1))
            {
                SpiderTaskEntity ste = (SpiderTaskEntity)localIterator2.next();
                BArticleInfoEntity bArticleInfo = new BArticleInfoEntity();
                if (bBrandInfoEntity != null) {
                    bArticleInfo.setArticleBrandId(bBrandInfoEntity.getId());
                } else if (articleTypeInfoEntity != null) {
                    bArticleInfo.setArticleTypeId(articleTypeInfoEntity.getId());
                }
                if ((bArticleInfo.getArticleBrandId() != null) || (bArticleInfo.getArticleTypeId() != null))
                {
                    bArticleInfo.setCreateTime(new Date());
                    bArticleInfo.setModifyTime(new Date());
                    bArticleInfo.setArticleSource(Integer.valueOf(6));
                    bArticleInfo.setArticleStatus(Integer.valueOf(1));
                    bArticleInfo.setSpiderProcessStatus(Integer.valueOf(1));
                    bArticleInfo.setArticleVersionNum(Integer.valueOf(2));

                    SysUserEntity curUser = getUser();
                    bArticleInfo.setCreateUser(curUser.getUsername());

                    bArticleInfo.setArticleTitle(ste.getArticleTitle());

                    String articleImgUrl = ste.getArticleThumbnail();
                    if ((ste.getArticleThumbnail() != null) && (!ste.getArticleThumbnail().contains(AliyunOssClientUtil.ossImgUrl))) {
                        articleImgUrl = AliyunOssClientUtil.uploadFileByFileUrl2(ste.getArticleThumbnail());
                    }
                    bArticleInfo.setArticleImgUrl(articleImgUrl);

                    String articleContent = updateImgs(ste.getArticleContent());

                    bArticleInfo.setArticleContent(articleContent);
                    bArticleInfo.setArticleDesc(ste.getArticleBrief());
                    bArticleInfo.setSUrl(ste.getUrl());
                    bArticleInfo.setSId(ste.getId().toString());
                    bArticleInfo.setSType("爬虫导入");

                    this.bArticleInfoService.save(bArticleInfo);
                    logger.info("新增文章:" + bArticleInfo.getArticleTitle());

                    this.bArticleInfoService.updateImportStute(ste.getId());
                    localInteger1 = total;
                }
            }
        }
        return R.ok().put("total", total);
    }

    private String updateImgs(String articleContent)
            throws IOException
    {
        Document document = null;
        document = Jsoup.parse(articleContent);

        Elements imgElements = document.select("img");
        for (Element img : imgElements)
        {
            String src = "";
            if ((img.attr("src") != null) && (!img.attr("src").contains(AliyunOssClientUtil.ossImgUrl)))
            {
                src = AliyunOssClientUtil.uploadFileByFileUrl2(img.attr("src"));
                img.attr("src", src);
            }
        }
        return document.body().html();
    }

    @RequestMapping({"/importArticle2"})
    @RequiresPermissions({"sys:barticleinfo:save"})
    public R importArticle2()
            throws Exception
    {
        List<SpiderTaskEntity> spiderTaskEntities = this.bArticleInfoService.getSpiderTaskList();
        Integer total = Integer.valueOf(0);
        Integer localInteger1;
        if ((spiderTaskEntities != null) && (spiderTaskEntities.size() > 0))
        {
            Integer localInteger2;
            for (Iterator localIterator = spiderTaskEntities.iterator(); localIterator.hasNext(); localInteger2 = total = Integer.valueOf(total.intValue() + 1))
            {
                SpiderTaskEntity ste = (SpiderTaskEntity)localIterator.next();
                BArticleInfoEntity bArticleInfo = new BArticleInfoEntity();

                bArticleInfo.setCreateTime(new Date());
                bArticleInfo.setModifyTime(new Date());
                bArticleInfo.setArticleSource(Integer.valueOf(1));
                bArticleInfo.setArticleStatus(Integer.valueOf(1));
                bArticleInfo.setSpiderProcessStatus(Integer.valueOf(1));
                bArticleInfo.setArticleVersionNum(Integer.valueOf(2));
                bArticleInfo.setArticleBrandId(Integer.valueOf(0));

                bArticleInfo.setArticleTitle(ste.getArticleTitle());
                bArticleInfo.setArticleImgUrl(ste.getArticleThumbnail());
                bArticleInfo.setArticleDesc(ste.getArticleBrief());
                bArticleInfo.setSUrl(ste.getUrl());

                bArticleInfo.setArticleContent(ste.getArticleContent());

                this.bArticleInfoService.save(bArticleInfo);
                logger.info("新增文章:" + bArticleInfo.getArticleTitle());
                localInteger1 = total;
            }
        }
        return R.ok().put("total", total);
    }

    @RequestMapping({"/updateHide"})
//    @RequiresPermissions({"sys:barticleinfo:update"})
    public R updateHide(@RequestBody BArticleInfoEntity bArticleInfo)
            throws Exception {
        ValidatorUtils.validateEntity(bArticleInfo, new Class[0]);

        Integer[] articleIds = bArticleInfo.getArticleIds();
        if (articleIds.length > 0 && (bArticleInfo.getArticleStatus() != null)) {
            for (Integer id : articleIds) {
                String cacheKey = id + "ArticleDetailInfoKey";
                System.out.println(cacheKey);
                this.redisCacheUtil.removeSingleCacheMaster(cacheKey);

                BArticleInfoEntity dataArticleInfo = this.bArticleInfoService.getById(id);
                dataArticleInfo.setRedisStoreStatus(Integer.valueOf(2));
                dataArticleInfo.setArticleStatus(bArticleInfo.getArticleStatus());
                if (dataArticleInfo.getArticleBrandId() != null) {
                    // 删除品牌 top50 缓存 start
                    String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + dataArticleInfo.getArticleBrandId();
                    redisCacheUtil.removeSingleCacheMaster(articleBrandIdKey);
                    // 删除品牌 top50 缓存 end
                    this.redisCacheUtil.removeSingleCache("recommendHotArticleInfo2ByBrandForHotValue" + dataArticleInfo.getArticleBrandId());
                    this.redisCacheUtil.removeSingleCache("recommendHotArticleInfoByBrandForHotValue" + dataArticleInfo.getArticleBrandId());
                    this.redisCacheUtil.removeSingleCache("recommendHotVideoInfoByBrandForHotValue" + dataArticleInfo.getArticleBrandId());
                    //this.redisCacheUtil.removeSingleCache("platformBrandArticle" + dataArticleInfo.getArticleBrandId());
                }
                if (dataArticleInfo.getArticleTypeId() != null) {
                    // 删除分类 top50 缓存 start
                    String articleTypeIdKey = SysConstant.PLANT_FORM_TYPE_ARTICLE_TOP50 + dataArticleInfo.getArticleTypeId();
                    redisCacheUtil.removeSingleCacheMaster(articleTypeIdKey);
                    // 删除分类 top50 缓存 end
                    this.redisCacheUtil.removeSingleCache("recommendHotArticleInfo2ByTypeForHotValue" + dataArticleInfo.getArticleTypeId());
                    this.redisCacheUtil.removeSingleCache("recommendHotArticleInfoByTypeForHotValue" + dataArticleInfo.getArticleTypeId());
                    this.redisCacheUtil.removeSingleCache("recommendHotVideoInfoByTypeForHotValue" + dataArticleInfo.getArticleTypeId());
                    //this.redisCacheUtil.removeSingleCache("platformTypeArticle" + dataArticleInfo.getArticleTypeId());
                }

                dataArticleInfo.setModifyTime(new Date());
                this.bArticleInfoService.updateById(dataArticleInfo);

            }
        }

        HttpGetPostUtils.delCache(this.serviceUrls, "ArticleInfoMapper");
        return R.ok();
    }

    @RequestMapping({"/update"})
    @RequiresPermissions({"sys:barticleinfo:update"})
    public R update(@RequestBody BArticleInfoEntity bArticleInfo)
            throws Exception
    {
        ValidatorUtils.validateEntity(bArticleInfo, new Class[0]);
        String cacheKey = bArticleInfo.getId() + "ArticleDetailInfoKey";
        System.out.println(cacheKey);
        //if ((bArticleInfo.getArticleStatus() != null) && (bArticleInfo.getArticleStatus().intValue() == 0)) {
        if ((bArticleInfo.getArticleStatus() != null) ) {
            //bArticleInfo.setArticleStatus(Integer.valueOf(0));
            bArticleInfo.setRedisStoreStatus(Integer.valueOf(2));

            this.redisCacheUtil.removeSingleCacheMaster(cacheKey);

            BArticleInfoEntity dataArticleInfo = this.bArticleInfoService.getById(bArticleInfo.getId());
            if (dataArticleInfo.getArticleBrandId() != null) {
                // 删除品牌 top50 缓存 start
                String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + dataArticleInfo.getArticleBrandId();
                redisCacheUtil.removeSingleCacheMaster(articleBrandIdKey);
                // 删除品牌 top50 缓存 end
                this.redisCacheUtil.removeSingleCache("recommendHotArticleInfo2ByBrandForHotValue" + dataArticleInfo.getArticleBrandId());
                this.redisCacheUtil.removeSingleCache("recommendHotArticleInfoByBrandForHotValue" + dataArticleInfo.getArticleBrandId());
                this.redisCacheUtil.removeSingleCache("recommendHotVideoInfoByBrandForHotValue" + dataArticleInfo.getArticleBrandId());
                //this.redisCacheUtil.removeSingleCache("platformBrandArticle" + dataArticleInfo.getArticleBrandId());
            }
            if (dataArticleInfo.getArticleTypeId() != null) {
                // 删除分类 top50 缓存 start
                String articleTypeIdKey = SysConstant.PLANT_FORM_TYPE_ARTICLE_TOP50 + dataArticleInfo.getArticleTypeId();
                redisCacheUtil.removeSingleCacheMaster(articleTypeIdKey);
                // 删除分类 top50 缓存 end
                this.redisCacheUtil.removeSingleCache("recommendHotArticleInfo2ByTypeForHotValue" + dataArticleInfo.getArticleTypeId());
                this.redisCacheUtil.removeSingleCache("recommendHotArticleInfoByTypeForHotValue" + dataArticleInfo.getArticleTypeId());
                this.redisCacheUtil.removeSingleCache("recommendHotVideoInfoByTypeForHotValue" + dataArticleInfo.getArticleTypeId());
                //this.redisCacheUtil.removeSingleCache("platformTypeArticle" + dataArticleInfo.getArticleTypeId());
            }
        }


        bArticleInfo.setModifyTime(new Date());
        this.bArticleInfoService.updateById(bArticleInfo);
        HttpGetPostUtils.delCache(this.serviceUrls, "ArticleInfoMapper");
        return R.ok();
    }

    @RequestMapping({"/updateInfo"})
    @RequiresPermissions({"sys:barticleinfo:update"})
    public R updateInfo(@RequestBody BArticleInfoEntity bArticleInfo)
            throws Exception
    {
        if ((bArticleInfo.getBrandName().equals("")) && (bArticleInfo.getArticleTypeName().equals(""))) {
            return R.error("你好，请选择文章品牌或文章分类！");
        }
        if ((bArticleInfo.getArticleTitle() == null) || (bArticleInfo.getArticleDesc() == null) || (bArticleInfo.getArticleContent() == null)) {
            return R.error("你好，文章标题、概述、内容不能为空！");
        }

        for(String k: SysConstant.KeyWorks){
            if(bArticleInfo.getArticleTitle()!=null && bArticleInfo.getArticleTitle().contains(k)){
                return R.error("标题中不能包含“"+k+"”，请检查后修正.");
            }
            if(bArticleInfo.getArticleDesc()!=null && bArticleInfo.getArticleDesc().contains(k)){
                return R.error("配文中不能包含“"+k+"”，请检查后修正.");
            }
        }

        // 使用默认单例（加载默认词典）
        SensitiveFilter filter =new SensitiveFilter(new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("sensi_words.txt"), StandardCharsets.UTF_8)));
//        SensitiveFilter filter = SensitiveFilter.DEFAULT;

        //文章标题+"占位符"，防止工具类筛选掉两个字符串的标题
        String textTitle = bArticleInfo.getArticleTitle()+"文章标题";

        //文章标题进行过滤
        String filtedTitle = filter.filter(textTitle, '▓')+"文章标题";

        // 如果未过滤，则返回输入的String引用
        if (filtedTitle.contains("▓▓")) {
            // 句子中有敏感词
            //找出可能第一个敏感词语
            int length = Math.min(filtedTitle.length(), textTitle.length());
            int pos = 0;
            while (pos < length) {
                if (0 != (filtedTitle.charAt(pos) ^ textTitle.charAt(pos))) {
                    break;
                }
                pos++;
            }

            return R.error("您好，文章标题中含有敏感关键字【"+ textTitle.substring(pos, pos + 2) +"】哦");
        }

        //文章概述
        String textDesc = bArticleInfo.getArticleDesc()+"文章概述";

        //文章概述进行过滤
        String filtedDesc = filter.filter(textDesc, '▓')+"文章概述";

        // 如果未过滤，则返回输入的String引用
        if (filtedDesc.contains("▓▓")) {
            // 句子中有敏感词
            //找出可能第一个敏感词语
            int length = Math.min(filtedDesc.length(), textDesc.length());
            int pos = 0;
            while (pos < length) {
                if (0 != (filtedDesc.charAt(pos) ^ textDesc.charAt(pos))) {
                    break;
                }
                pos++;
            }

            return R.error("您好，文章概述中含有敏感关键字【"+ textDesc.substring(pos, pos + 2) +"】哦");
        }

        //文章内容
        String textContent = bArticleInfo.getArticleContent();

        //文章内容进行过滤
        String filtedContent = filter.filter(textContent, '▓');

        // 如果未过滤，则返回输入的String引用
        if (filtedContent.contains("▓▓")) {
            // 句子中有敏感词
            //找出可能第一个敏感词语
            int length = Math.min(filtedContent.length(), textContent.length());
            int pos = 0;
            while (pos < length) {
                if (0 != (filtedContent.charAt(pos) ^ textContent.charAt(pos))) {
                    break;
                }
                pos++;
            }

            return R.error("您好，文章内容中含有敏感关键字【"+ textContent.substring(pos, pos + 2) +"】哦");
        }
        ValidatorUtils.validateEntity(bArticleInfo, new Class[0]);
        String cacheKey = bArticleInfo.getId() + "ArticleDetailInfoKey";
        System.out.println(cacheKey);
        if ((bArticleInfo.getArticleStatus() != null) && (bArticleInfo.getArticleStatus().intValue() == 0))
        {
            bArticleInfo.setArticleStatus(Integer.valueOf(0));
            bArticleInfo.setRedisStoreStatus(Integer.valueOf(2));
        }

//        Boolean redisDel = Boolean.valueOf(this.redisCacheUtil.removeSingleCacheMaster(cacheKey));
        Boolean redisDel = Boolean.valueOf(this.redisCacheUtil.removeSingleCache(cacheKey));// 刪除文章緩存 2022-03-30

        System.out.println("***** BArticleInfoController updateInfo redisDel:" + redisDel + " _ cacheKey:" + cacheKey);

        HttpGetPostUtils.delCache(this.serviceUrls, "ArticleInfoMapper");
        bArticleInfo.setModifyTime(new Date());

        bArticleInfo.setArticleBrandId(null);
        bArticleInfo.setArticleTypeId(null);

//        SysUserEntity curUser = getUser();
//        bArticleInfo.setCreateUser(curUser.getUsername());
        // 先删除关联的头条标题
        this.bArticleInfoService.delHeadlineRelation(bArticleInfo.getId());
        if (!bArticleInfo.getBrandName().equals(""))
        {
            BBrandInfoEntity brandInfoEntity = this.bBrandInfoService.queryByName(bArticleInfo.getBrandName());
            if (brandInfoEntity != null)
            {
                bArticleInfo.setArticleBrandId(brandInfoEntity.getId());
                // 删除品牌 top50 缓存 start
                String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + brandInfoEntity.getId();
                redisCacheUtil.removeSingleCacheMaster(articleBrandIdKey);
                // 删除品牌 top50 缓存 end
                this.bArticleInfoService.setNullArticleTypeId(bArticleInfo.getId());
                this.bArticleInfoService.updateById(bArticleInfo);
                // 向头条标题添加关联 start yl 20200624
                if (StringUtils.isNoneBlank(bArticleInfo.getHeadlineTitleIds())){
                    this.headlineRelation(bArticleInfo.getId(), Arrays.stream(bArticleInfo.getHeadlineTitleIds()
                            .split(","))
                            .map(s -> Integer.valueOf(s.trim()))
                            .collect(Collectors.toList()));
                }
                // 向头条标题添加关联 end yl 20200624
                // 文章公众号关联
                BArticleGzh bArticleGzhSave = new BArticleGzh();
                // 文章id
                bArticleGzhSave.setArticleId(bArticleInfo.getId());
                // 公众号标识
                bArticleGzhSave.setGzhCode(bArticleInfo.getGzhCode());
                // 先删除
                if(this.bArticleGzhService.queryByArticleId(bArticleInfo.getId()) != null) {
                    this.bArticleGzhService.deleteByArticleId(bArticleInfo.getId());
                }
                // 再保存
                if((bArticleGzhSave.getGzhCode() != null) && (!bArticleGzhSave.getGzhCode().equals("-1")) && (!"".equals(bArticleGzhSave.getGzhCode().trim()))) {
                    this.bArticleGzhService.insertOne(bArticleGzhSave);
                }
                return R.ok();
            }
            return R.error("所选的文章品牌不存在");
        }
        if (!bArticleInfo.getArticleTypeName().equals(""))
        {
            BArticleTypeInfoEntity articleTypeInfoEntity = this.bArticleTypeInfoService.queryByName(bArticleInfo.getArticleTypeName());
            if (articleTypeInfoEntity != null)
            {
                bArticleInfo.setArticleTypeId(articleTypeInfoEntity.getId());
                // 删除分类 top50 缓存 start
                String articleTypeIdKey = SysConstant.PLANT_FORM_TYPE_ARTICLE_TOP50 + articleTypeInfoEntity.getId();
                redisCacheUtil.removeSingleCacheMaster(articleTypeIdKey);
                // 删除分类 top50 缓存 end
                this.bArticleInfoService.setNullArticleBrandId(bArticleInfo.getId());
                this.bArticleInfoService.updateById(bArticleInfo);
                // 向头条标题添加关联 start yl 20200624
                if (StringUtils.isNoneBlank(bArticleInfo.getHeadlineTitleIds())){
                    this.headlineRelation(bArticleInfo.getId(), Arrays.stream(bArticleInfo.getHeadlineTitleIds()
                            .split(","))
                            .map(s -> Integer.valueOf(s.trim()))
                            .collect(Collectors.toList()));
                }
                // 向头条标题添加关联 end yl 20200624
                // 文章公众号关联
                BArticleGzh bArticleGzhSave = new BArticleGzh();
                // 文章id
                bArticleGzhSave.setArticleId(bArticleInfo.getId());
                // 公众号标识
                bArticleGzhSave.setGzhCode(bArticleInfo.getGzhCode());
                // 先删除
                if(this.bArticleGzhService.queryByArticleId(bArticleInfo.getId()) != null) {
                    this.bArticleGzhService.deleteByArticleId(bArticleInfo.getId());
                }
                // 再保存
                if((bArticleGzhSave.getGzhCode() != null) && (!bArticleGzhSave.getGzhCode().equals("-1")) && (!"".equals(bArticleGzhSave.getGzhCode().trim()))) {
                    this.bArticleGzhService.insertOne(bArticleGzhSave);
                }
                return R.ok();
            }
            return R.error("所选的文章类型不存在");
        }
        logger.info("更新文章:" + bArticleInfo.getArticleTitle());
        return R.error("新增文章失败");
    }

    @RequestMapping({"/delete"})
    @RequiresPermissions({"sys:barticleinfo:delete"})
    public R delete(@RequestBody Integer[] ids)
    {
        this.bArticleInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @RequestMapping({"/commit1"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    @ResponseBody
    public R request(@RequestBody String wxArticleUrl)
            throws Exception
    {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("http://192.168.5.147:8888/spiderChaoVcardInfo/");
        String json = "{\"wxArticleUrl\":" + wxArticleUrl + "}";
        StringEntity postingString = new StringEntity(json);
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());

        JSONObject jsonObject = JSONObject.fromObject(content);
        String articleContent = jsonObject.get("content").toString();
        return R.ok().put("content", jsonObject).put("family", articleContent);
    }

    @RequestMapping({"/commit"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    @ResponseBody
    public R requests(@RequestBody String wxArticleUrl)
            throws Exception
    {
        String content = getContentByUrl(wxArticleUrl);

        JSONObject jsonObject = JSONObject.fromObject(content);

        String contents = jsonObject.get("data").toString();
        String code = jsonObject.get("code").toString();
        if (code.equals("2")) {
            return R.error("文章内容过短。");
        }
        if (code.equals("3")) {
            return R.error("文章内容过短。");
        }
        if (code.equals("4")) {
            return R.error("文章可能涉嫌违规");
        }
        jsonObject = JSONObject.fromObject(contents);
        String articleContent = jsonObject.get("article_content").toString();

        articleContent = getAfterArticleContent(articleContent);
        return R.ok().put("content", jsonObject).put("family", articleContent);
    }

    private String getContentByUrl(String wxArticleUrl)
            throws Exception
    {
        HttpClient httpClient = HttpClientBuilder.create().build();
        String profile = SpringContextUtil.getActiveProfile();
        String url = "";
        if (profile.equals("dev")) {
            url = "http://120.78.222.19/snippetsFormatText/";
        } else {
            url = "http://120.78.222.19/snippetsFormatText/";
        }
        HttpPost post = new HttpPost(url);
        String json = "{\"wxArticleUrl\":" + wxArticleUrl + "}";
        StringEntity postingString = new StringEntity(json);
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());
        return content;
    }

    private String getAfterArticleContent(String articleContent)
    {
        Document htmlDoc = Jsoup.parse(articleContent);

        Element headDiv = htmlDoc.select("div#js_content").first();
        headDiv.attr("style", "max-width: 100%;");

        Elements imgs = htmlDoc.select("img");
        for (Element e : imgs) {
            e.attr("src", e.attr("data-src"));
        }
        logger.info("*******articleContent:" + htmlDoc.html());
        return htmlDoc.html();
    }

    @RequestMapping({"/informArticel"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    public R informArticel(@RequestParam Map<String, Object> params)
    {
        System.out.println(params);
        Query query = new Query(params);
        List<BArticleInfoEntity> brandList = this.bArticleInfoService.informArticel(query);
        System.out.println(brandList.size());
        for (BArticleInfoEntity bArticleInfoEntity : brandList)
        {
            if ((bArticleInfoEntity.getArticleSource() != null) && (bArticleInfoEntity.getArticleSource().intValue() == 1)) {
                bArticleInfoEntity.setUserName("管理员");
            }
            if (bArticleInfoEntity.getArticleTypeId() == null)
            {
                BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.getById(bArticleInfoEntity.getArticleBrandId());
                if (bBrandInfoEntity != null) {
                    bArticleInfoEntity.setArticleTypeName(bBrandInfoEntity.getBrandName());
                }
            }
            else
            {
                BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.getById(bArticleInfoEntity.getArticleTypeId());
                if (bArticleTypeInfoEntity != null) {
                    bArticleInfoEntity.setArticleTypeName(bArticleTypeInfoEntity.getArticleTypeName());
                }
            }
        }
        int total = this.bArticleInfoService.informArticelTotal(query).intValue();
        PageUtils pageUtil = new PageUtils(brandList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @RequestMapping({"/putArticle"})
    @ResponseBody
    public R putArticel()
            throws Exception
    {
        System.out.println("dsaaaafsafasfafsaf");
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("http://192.168.5.63:8888/spiderArticleDesc/");
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = JSONObject.fromObject(content);
        String contents = jsonObject.get("data").toString();
        jsonObject = JSONObject.fromObject(contents);
        BArticleInfoEntity articleInfo = new BArticleInfoEntity();
        if (jsonObject.get("article_title").toString() == null) {
            return R.error("");
        }
        articleInfo.setArticleTitle(jsonObject.get("article_title").toString());
        articleInfo.setArticleImgUrl(jsonObject.get("article_img_url").toString());
        articleInfo.setArticleContent(jsonObject.get("content").toString());
        articleInfo.setArticleDesc(jsonObject.get("article_brief").toString());
        int article_brand_id = Integer.parseInt(jsonObject.get("article_brand_id").toString());
        if (article_brand_id != 0) {
            articleInfo.setArticleBrandId(Integer.valueOf(article_brand_id));
        } else {
            articleInfo.setArticleTypeId(Integer.valueOf(Integer.parseInt(jsonObject.get("article_type_id").toString())));
        }
        articleInfo.setArticleHotScore(Integer.valueOf(Integer.parseInt(jsonObject.get("article_hot_score").toString())));
        articleInfo.setCreateTime(new Date());
        articleInfo.setArticleSource(Integer.valueOf(1));
        articleInfo.setArticleStatus(Integer.valueOf(1));
        articleInfo.setSpiderProcessStatus(Integer.valueOf(1));
        articleInfo.setArticleVersionNum(Integer.valueOf(2));
        this.bArticleInfoService.save(articleInfo);
        return R.ok();
    }

    /**
     * 合并文章到品牌
     */
    @Transactional
    @RequestMapping("/merge")
    public R merge(@RequestBody BArticleInfoEntity bArticleInfo){
        ValidatorUtils.validateEntity(bArticleInfo);
        BBrandInfoEntity brandInfo = bBrandInfoService.queryByName(bArticleInfo.getBrandName());
        if(brandInfo == null){
            return R.error();
        }
        Integer[] articleIds = bArticleInfo.getArticleIds();
        if(articleIds.length > 0){
            for (Integer id : articleIds) {
                BArticleInfoEntity info = this.bArticleInfoService.getById(id);
                if(info != null){
                    info.setArticleTypeId(null);
                    info.setArticleBrandId(brandInfo.getId());

                    this.bArticleInfoService.save(info);
//                    System.out.println(info.getId());
                }
            }
        }
        return R.ok();
    }

    /**
     * 合并文章到行业
     */
    @Transactional
    @RequestMapping("/merge2")
    public R merge2(@RequestBody BArticleInfoEntity bArticleInfo){
        ValidatorUtils.validateEntity(bArticleInfo);


        BArticleTypeInfoEntity articleTypeInfo = bArticleTypeInfoService.queryByName(bArticleInfo.getArticleTypeName());
        if(articleTypeInfo == null){
            return R.error();
        }
        Integer[] articleIds = bArticleInfo.getArticleIds();
        if(articleIds.length > 0){
            for (Integer id : articleIds) {
                BArticleInfoEntity info = this.bArticleInfoService.getById(id);
                if(info != null){
                    info.setArticleTypeId(articleTypeInfo.getId());
                    info.setArticleBrandId(null);
                    info.setCreateUser(getUser().getUsername());// 创建人
                    info.setArticleSource(Integer.valueOf(1));// 文章来源：平台
                    info.setUserId(null);// user_id 清空
                    info.setShareArticleSourceId(null);// 分享来源文章id 清空

                    this.bArticleInfoService.save(info);
//                    System.out.println(info.getId());
                }
            }
        }
        return R.ok();
    }

    /**
     * 按文章ID获取用户分享详情(分页)
     * @param params
     * @return
     */
    @RequestMapping("/userShareInfo")
    public R getUserShareInfo(@RequestParam Map<String, Object> params) {
        if (params.get("id") == null) {
            return R.error("访问失败");
        }
        if (params.get("resourceType") == null || params.get("resourceType").equals("")) {
            params.put("resourceType", 1);
        }
        Query query = new Query(params);
        List<BUserShareArticleInfoEntity> list = bUserShareArticleInfoService.getUserShareInfo(query);
        int total = bUserShareArticleInfoService.getUserShareInfoTotal(query);
        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

    @RequestMapping("/getUserShareCountByArticleId")
    public R getUserShareCountByArticleId(@RequestParam Map<String, Object> params) {
        if (params.get("id") == null) {
            return R.error("访问失败");
        }
        if (params.get("resourceType") == null || params.get("resourceType").equals("")) {
            params.put("resourceType", 1);
        }
        int userShareCount = bUserShareArticleInfoService.getUserShareInfoTotal(params);
        return R.ok().put("userShareCount", userShareCount);
    }

    /**
     * 按文章ID获取用户换成我的文章的详情(分页)
     * @param params
     * @return
     */
    @RequestMapping("/userCopyInfo")
    public R getUserCopyInfo(@RequestParam Map<String, Object> params) {
        if (params.get("id") == null) {
            return R.error("访问失败");
        }
        if (params.get("resourceType") == null || params.get("resourceType").equals("")) {
            params.put("resourceType", 1);
        }
        Query query = new Query(params);
        List<BUserShareArticleInfoEntity> list = bArticleInfoService.getUserCopyInfo(query);
        int total = bArticleInfoService.getUserCopyInfoTotal(query);
        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

    @RequestMapping("/getUserCopyCountByArticleId")
    public R getUserCopyCountByArticleId(@RequestParam Map<String, Object> params) {
        if (params.get("id") == null) {
            return R.error("访问失败");
        }
        if (params.get("resourceType") == null || params.get("resourceType").equals("")) {
            params.put("resourceType", 1);
        }
        int userCopyCount = bArticleInfoService.getUserCopyInfoTotal(params);
        return R.ok().put("userCopyCount", userCopyCount);
    }

    @RequestMapping("/getUserArticleCount/{userId}")
    public R getUserArticleCount(@PathVariable("userId") Integer userId) {
        if (userId == null || userId <= 0)
            return R.error("用户不存在");
        int userArticleCount = bArticleInfoService.getUserArticleCount(userId);
        return R.ok().put("userArticleCount", userArticleCount);
    }

    @RequestMapping("/getUserShareArticleCount/{userId}")
    public R getUserShareArticleCount(@PathVariable("userId") Integer userId) {
        if (userId == null || userId <= 0)
            return R.error("用户不存在");
        int userShareArticleCount = bUserShareArticleInfoService.getUserShareArticleCount(userId);
        return R.ok().put("userShareArticleCount", userShareArticleCount);
    }

    @RequestMapping("/getProgressInfo")
    public R getProgressInfo() {
        Map<String, Object> progressInfo =  bArticleInfoService.getProgressInfo();
        return R.ok().put("progressInfo", progressInfo);
    }

    @RequestMapping("/updateArticleDesc")
    public R updateArticleDesc(@RequestParam("articleDesc") String articleDesc,
                               @RequestParam("articleNewDesc") String[] articleNewDesc,
                               @RequestParam("type") Integer type) {
        if (articleDesc == null || articleDesc.trim() == "") {
            return R.error("文章标题不能为空");
        }
        if (articleNewDesc == null || articleNewDesc.length == 0) {
            return R.error("替换的文章标题不能为空");
        }
        bArticleInfoService.updateArticleDesc(articleDesc, articleNewDesc, type);
        return R.ok();
    }

    @RequestMapping("/updateArticleContent")
    public R updateArticleDesc(@RequestParam("brandId") Integer brandId, @RequestParam("content") String content, @RequestParam("newContents") String[] newContents) {
        if (brandId == null) {
            return R.error("品牌不能为空");
        }
        if (content == null || content.trim() == "") {
            return R.error("文章内容不能为空");
        }
        if (newContents == null || newContents.length == 0) {
            return R.error("替换的文章内容不能为空");
        }
        bArticleInfoService.updateArticleContent(brandId, content, newContents);
        return R.ok();
    }

    @RequestMapping("/deleteHalfYearAgoArticle")
    public R deleteHalfYearAgoArticle() {
        bArticleInfoService.deleteHalfYearAgoArticle();
        return R.ok();
    }

    @RequestMapping({"/beginner/{id}"})
    public R beginner(@PathVariable("id") Integer id){
        BArticleInfoEntity bArticleInfo = this.bArticleInfoService.getBeginnerArticleById(id);
        return R.ok().put("bArticleInfo", bArticleInfo);
    }
}
